
propsage.namespace("prestige.receipt");

prestige.receipt.calculateCommissions = (function($, ui) {

	function initComponents()
	{
		$('#regeneratePayableItemsDenyDialog').dialog({
			'width': 500,
			'height': 400,
			'autoOpen': false,
			'resizable': false,
			'buttons': {
				'Cancel': {
					'text': 'OK',
					'click': onDialogCancel
				}
			}
		});
		
		$('input:text[class="input-percent"]').each(function(i){
			if(editablePolicy == 0){
				$(this).attr('readonly', true);
			}
			$(this).autoNumeric('init' );
			
		});
		
		$('input:text[class="input-value"]').each(function(i){
			if(editablePolicy == 0){
				$(this).attr('readonly', true);
			}
			$(this).autoNumeric('init', {
				aSign: '$ '
			} );
		});
	}

	function initEventHandlers()
	{
		$('#generate').click(onBtnGenerateClick);
		$('#promote-link').click(onPromoteLinkClick);
		$('.input-percent').change(onPercentChange);
		$('.input-value').change(onValueChange);
	}
	
	function onPercentChange()
	{
		var gross_amount = $(this).closest('tr').find('.input-gross').val();
		var new_percent =  $(this).autoNumeric('get');
		$(this).closest('tr').find('.input-value').autoNumeric('set', (gross_amount * new_percent / 100));
		
		if($(this).closest('div').hasClass('basic-comm-details')){		
			$(this).closest('div').find('span.comm-remarks').remove();	//admin overrides min, max, riders, etc
		}
		
		var $table = $(this).closest('table');
		var $section = $(this).closest('div.section');
		calculateAgentTotal($table);
		calculateAllAgentsTotal($section);
		calculateAgencyBalance($section);
	}
	
	function onValueChange()
	{
		var gross_amount = $(this).closest('tr').find('.input-gross').val();
//		var new_value = Number(($(this).val()).replace(/[$,]+/g,""));
		var new_value = $(this).autoNumeric('get');
		$(this).closest('tr').find('.input-percent').autoNumeric('set', (new_value / gross_amount * 100));
		
		if($(this).closest('td').prev().find('div').hasClass('basic-comm-details')){
			$(this).closest('td').prev().find('span.comm-remarks').remove();	//admin overrides min, max, riders, etc
		}
		
		var $table = $(this).closest('table');
		var $section = $(this).closest('div.section');
		calculateAgentTotal($table);
		calculateAllAgentsTotal($section);
		calculateAgencyBalance($section);
	}
	
	function calculateAgentTotal($table)
	{
		var agentTotal = 0;
		$table.find('.input-value').each(function(i){
//			agentTotal += Number(($(this).val()).replace(/[$,]+/g,""));
			agentTotal += $(this).autoNumeric('get');
		});
		$table.find('.agent-total span').html(agentTotal.toFixed(2));
	}
	
	
	function calculateAllAgentsTotal($section)
	{
		var allAgentsTotal = 0;
		$section.find('.agent-total span').each(function(i){
			allAgentsTotal += Number(($(this).text()).replace(/[$,]+/g,""));
		});

		$section.find('span.all-agent-total').html(allAgentsTotal.toFixed(2));
		$section.find('.input-all-agent-total').val(allAgentsTotal);
	}

	
	function calculateAgencyBalance($section)
	{
//		var amount_received = Number(($section.find('.amount-received strong').text()).replace(/[$A-z,]+/g,""));
//		var int_agents_total = Number(($section.find('.all-agent-total strong').text()).replace(/[$A-z,]+/g,""));
//		var ext_agents_total = Number(($section.find('.external-agent-total strong').text()).replace(/[$A-z,]+/g,""));
//		var amount_reserved_for_gst = Number(($section.find('.amount-reserved-for-gst strong').text()).replace(/[$A-z,]+/g,""));
//		var agency_balance = amount_received - int_agents_total - ext_agents_total - amount_reserved_for_gst;
		
		var amount_received = $section.find('span.amount-received').text(); 
		var int_agents_total = $section.find('span.all-agent-total').text(); 
		var ext_agents_total = $section.find('span.external-agent-total').text(); 
		var amount_reserved_for_gst = $section.find('span.amount-reserved-for-gst').text(); 
		var agency_balance = amount_received - int_agents_total - ext_agents_total - amount_reserved_for_gst;
		
		$section.find('.agency-balance strong').html('$ ' + agency_balance.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
		$section.find('.input-agency-balance').val(agency_balance);
		if(agency_balance < 0){
			$section.find('.agency-balance strong').addClass('red');
		} else {
			$section.find('.agency-balance strong').removeClass('red');
		}
	}
	
	function onBtnGenerateClick(event)
	{
		var positiveBalance = true;
		$('.input-agency-balance').each(function(i){
			var balance = Math.round($(this).val()*100)/100;
			if(balance < 0.00){
				positiveBalance = false;
			}
		});
		
		if(!positiveBalance){
			alert('Total payouts exceed amount received for transaction. \nPlease check your input amounts.');
			return false;
		}		
		
		$('input:text[class^="input-"]').each(function(i){
			var value = $(this).autoNumeric('get');
			$(this).val(value);
		});
		
		
		if (!$.isEmptyObject(existingPaymentVouchers)) {
			$('#regeneratePayableItemsDenyDialog').dialog("open");
			$("#pv-item-list").empty();
			var pv_list = "<p>";
			var pv_link = "";

			$.each(existingPaymentVouchers, function(i, val) {
				pv_link = baseUrl + '/paymentVoucher/'+ i; 
				pv_list += '\t Payment Voucher No: <a class="blue" href="' + pv_link + '" target="_blank">' + val + '</a> <br/>';
			});
			pv_list += '<h4 class="red">Berore re-generate payable items, You need to manually cancel all above Payment Vouchers.</h4></p>';
			
			$(pv_list).appendTo("#pv-item-list");
			return false;
		}
	}
	
	function onPromoteLinkClick()
	{
		var agentName = $('#agent-name').text();
		var result = confirm('Are you sure you want to promote ' + agentName  + '?');
		if (!result) {
			return false;
		}
	}

	function onDialogCancel() {
		$(this).dialog("close");
		location.reload();
	}

	$(document).ready(function() {
		initComponents();
		initEventHandlers();
	});

}(jQuery, propsage.ui));